package com.daocao.jy.view;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.daocao.jy.R;
import com.daocao.jy.activity.ChangePhoneActivity;
import com.daocao.jy.api.Api;
import com.daocao.jy.api.bean.LoginBean;
import com.daocao.jy.api.bean.ModifySendBean;
import com.daocao.jy.base.BaseActivity;
import com.daocao.jy.constant.UserInfoGlobal;
import com.daocao.jy.util.Network;
import com.daocao.jy.util.RxLifeUtil;
import com.daocao.jy.util.ToastUtil;
import com.daocao.jy.util.UI;
import com.daocao.jy.util.Util;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by xsooy-pc on 2017/4/24.
 */

public class LoginDialog extends Dialog {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.layout_title)
    FrameLayout layoutTitle;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_change_phone)
    TextView btnChangePhone;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.btn_agreement)
    TextView btnAgreement;
    private Context context;


    public LoginDialog(Context context) {
        this(context, R.style.DialogStyle);
    }

    public LoginDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
        initView();
    }

    private void initView() {
        setContentView(R.layout.dialog_login_phone);
        ButterKnife.bind(this);
        setCancelable(false);

        Window mWindow = getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = Util.getDisplayMetrics(context).widthPixels;
        lp.gravity = Gravity.BOTTOM;
        mWindow.setAttributes(lp);
    }

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setEnabled(false);
            btnSendCode.setText((millisUntilFinished / 1000) + "s");
            btnSendCode.setTextColor(0xFFCCCCCC);
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);

        btnSendCode.setText("获取验证码");
        btnSendCode.setTextColor(0xFFFB5E01);
    }

    public void getSms(String phone) {
        if (!Network.checkNetwork(context)) {
            ToastUtil.show(context, "网络连接失败");
            return;
        }

        ModifySendBean item = new ModifySendBean();
        item.phone = phone;
        ((BaseActivity) context).loadingDialog.show();
        Api.api_service.getSmsSend(item).compose(RxLifeUtil.checkOn(((BaseActivity) context))).
                doFinally(() -> {
                    try {
                        ((BaseActivity) context).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    timer.start();
                    ToastUtil.makeText(context, "发送成功，请注意查收");
                });
    }

    public void getLogin(String phone, String code) {
        if (!Network.checkNetwork(context)) {
            ToastUtil.show(context, "网络连接失败");
            return;
        }

        LoginBean item = new LoginBean();
        item.phone = phone;
        item.verify_code = code;
        ((BaseActivity) context).loadingDialog.show();
        Api.api_service.getLogin(item).compose(RxLifeUtil.checkOn(((BaseActivity) context))).
                doFinally(() -> {
                    try {
                        ((BaseActivity) context).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    UserInfoGlobal.saveLoginInfo(result.datas);
                    ToastUtil.makeText(context, "登录成功");
                    if (listener != null) {
                        listener.loginSuccess();
                    }
                    dismiss();
                });
    }

    @Override
    public void dismiss() {
        if (timer != null) {
            resetBtn();
        }
        super.dismiss();
    }

    private DialogDefaultClickListener listener;

    public LoginDialog setDialogClickListener(DialogDefaultClickListener listener) {
        this.listener = listener;
        return this;
    }

    @OnClick({R.id.btn_back, R.id.btn_send_code, R.id.btn_change_phone, R.id.btn_submit, R.id.btn_agreement})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_back:
                this.dismiss();
                break;
            case R.id.btn_send_code:
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(context, "手机号不能为空");
                    return;
                }
                getSms(UI.toString(editPhone));
                break;
            case R.id.btn_change_phone:
                Util.startActivity(context, ChangePhoneActivity.class);
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(context, "手机号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(context, "验证码不能为空");
                    return;
                }
                getLogin(UI.toString(editPhone), UI.toString(editCode));
                break;
            case R.id.btn_agreement:
                break;
        }
    }

    public interface DialogDefaultClickListener {
        public abstract void loginSuccess();

        public abstract void cancel();
    }
}
